import modelExtend from 'dva-model-extend'
import { list ,query} from 'services/financialAccountBalance'
import { lwjPageModel } from 'utils/model'
import { routerRedux } from 'dva/router';

export default modelExtend(lwjPageModel, {
  namespace: 'financialAccountBalance',
  state: {
    allItems: [],
    items: []
  },
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname }) => {
        if (pathname === '/financialAccountBalance') {
          dispatch({ type: 'query', payload: {} })
        }
      })
    }
  },
  effects: {
    * query({
      payload
    }, { select, call, put }) {
      yield put({
        type: 'asyncData',
        payload: {
          ...payload
        }
      });

      const pageOptions = yield select(({ financialAccountBalance }) => financialAccountBalance.pageOptions);
      const queryParam = yield select(({ financialAccountBalance }) => financialAccountBalance.queryParam);

      const queryPayload = {
        ...pageOptions,
        queryParam: {
          isQueryAccounts:true,
          ...queryParam
        },
      };
      const data = yield call(query, queryPayload);
      yield put({
        type: 'querySuccess',
        payload: {
          ...data
        }
      })
    },
    * list({
      payload
    }, { select, call, put }) {
      if (!_.isEmpty(payload) && !_.isEmpty(payload.name)) {
        let allItems = yield select(({ financialAccountBalance }) => financialAccountBalance.allItems);
        let items = yield select(({ financialAccountBalance }) => financialAccountBalance.items);
        items = _.filter(allItems, (item) => {
          return item.name.indexOf(payload.name) > -1;
        });
        yield put({
          type: 'filterSuccess',
          payload: {
            items: items
          }
        })
      } else {
        const data = yield call(list, payload);
        yield put({
          type: 'listSuccess',
          payload: {
            allItems: data.result,
            items: data.result
          }
        })
      }
    },
    * showDetail({
      payload
    }, { select, call, put }) {
      yield put(routerRedux.push('/financialAccountBalanceRecord/' + payload.id))
    }
  },
  reducers: {
    listSuccess(state, { payload }) {
      return {
        ...state,
        ...payload
      }
    },
    filterSuccess(state, { payload }) {
      return {
        ...state,
        items: payload.items
      }
    },
  }
})
